package com.example.administrator.damaiwang.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpUtil {

    public static final int TEXT_TYPE = 1;
    public static final int IMAGE_TYPE = 2;
    public static final int ERROR_TYPE = 3;
    private ExecutorService mPool;
    private Handler mHandler;

    public HttpUtil(Handler handler) {
        //构建线程池对象
        mPool = Executors.newFixedThreadPool(10);
        this.mHandler = handler;
    }

    public void loadData(final String path, final int type) {
        mPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(30000);
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = is.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);

                        }
                        baos.flush();
                        byte[] data = baos.toByteArray();
                        Message msg = Message.obtain();
                        if (type == TEXT_TYPE) {
                            String json = new String(data);
                            msg.what = TEXT_TYPE;
                            msg.obj = json;
                        } else if (type == IMAGE_TYPE) {
                            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                            msg.what = IMAGE_TYPE;
                            msg.obj = bitmap;
                        }
                        mHandler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what=ERROR_TYPE;
                    mHandler.sendMessage(msg);
                }
            }
        });
    }

}
